package org.luxor.commons.redis.config;

import org.luxor.commons.redis.annotation.RedisListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.LinkedHashSet;
import java.util.Set;


/**
 * 注册Redis消息接收者
 *
 * @author Mr.yan @date 2019/10/13
 */
public class RedisListenerRegistrar implements BeanPostProcessor {
    private static final Logger logger = LoggerFactory.getLogger(RedisListenerRegistrar.class);

    private final RedisMessageListenerContainer redisMessageListenerContainer;

    public RedisListenerRegistrar(RedisMessageListenerContainer redisMessageListenerContainer) {
        this.redisMessageListenerContainer = redisMessageListenerContainer;
    }

    @Nullable
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        RedisListener annotation = AnnotationUtils.findAnnotation(bean.getClass(),RedisListener.class);
        if (annotation != null) {
            String listenerMethod = annotation.listenerMethod();
            if (methodRequire(bean, listenerMethod)) {
                String[] value = annotation.value();
                String[] channel = annotation.channel();

                Set<Topic> topics = new LinkedHashSet<>(5);
                for (int i = 0; i < value.length; i++) {
                    topics.add(new ChannelTopic(value[i]));
                }
                for (int i = 0; i < channel.length; i++) {
                    topics.add(new ChannelTopic(channel[i]));
                }

                if (CollectionUtils.isEmpty(topics)) {
                    logger.warn("Redis事件接收者:[ {} ]中,@RedisListener未设置通道名. -> [@RedisListener(XXX))]", bean.getClass());
                    return bean;
                }

                Assert.notNull(redisMessageListenerContainer, "RedisMessageListenerContainer has not been instantiated yet");

                MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(bean, listenerMethod);
                messageListenerAdapter.afterPropertiesSet();
                redisMessageListenerContainer.addMessageListener(messageListenerAdapter, topics);
            }
        }
        return bean;
    }

    private boolean methodRequire(Object receiver, String listenerMethod) {
        try {
            receiver.getClass().getDeclaredMethod(listenerMethod, String.class, String.class);
        } catch (NoSuchMethodException e) {
            logger.warn("事件接收者:[ {} ]中,没实现准确的接收方法. -> [public void {}(String message,String topic)]", receiver.getClass(), listenerMethod);
            return false;
        }
        return true;
    }
}